package com.server.questionbank.snframe.mapper.QuestionBank;

import com.server.questionbank.snframe.domain.Homework.TExercises;
import com.server.questionbank.snframe.domain.QuestionBank.Exercises;
import com.server.questionbank.snframe.domain.QuestionBank.Question;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.StatementType;

import java.util.List;

@Mapper
public interface ExercisesMapper {
    /**
     * 查询题库列表信息
     * @return
     */
    @Select({
            "SELECT ",
            "       e.exercises_id AS exercisesId,", // 题目 ID
            "       CASE e.topic_status", // 题目状态
            "           WHEN 1 THEN 'success'", // 状态 1：已完成
            "           WHEN 2 THEN 'incomplete'", // 状态 2：未完成
            "           WHEN 3 THEN 'wrong'", // 状态 3：已写错
            "       END AS topicStatus,", // 题目状态描述
            "       e.title,", // 题目标题
            "       CASE e.difficulty", // 题目难度
            "           WHEN 1 THEN '简单'", // 难度 1：简单
            "           WHEN 2 THEN '中等'", // 难度 2：中等
            "           WHEN 3 THEN '困难'", // 难度 3：困难
            "       END AS difficulty,", // 题目难度
            "       e.accuracy,", // 题目正确率
            "       e.challenge_num AS challengeNum,", // 挑战次数
            "       e.exercise_type AS exerciseType,", // 题目类型
            "       e.data_type AS type,", // 题的类型
            "       e.question_stem AS questionStem,", // 题目描述
            "       c.course_id AS \"courseInfo.courseId\",", // 课程 ID
            "       c.course_name AS \"courseInfo.courseName\",", // 课程名称
            "       ch.chapter_id AS \"chapterInfo.chapterId\",", // 章节 ID
            "       ch.chapter_name AS \"chapterInfo.chapterName\",", // 章节名称
            "       q.question_title AS \"question.quesTitle\",", // 题目标题
            "       q.question_type AS \"question.questionType\",", // 题目类型
            "       q.answer_options AS \"question.answerOptions\",", // 题目选项
            "       q.answer AS \"question.answer\",", // 题目答案
            "       q.score AS \"question.score\",", // 分数
            "       q.analysis AS \"question.analysis\",", // 题目解析
            "       k.knowledge_content AS \"tKnowledge.knowledgeContent\"", // 知识点概述
            "FROM T_exercises e", // 题目表
            "LEFT JOIN exec_knowledge ek ON e.exercises_id = ek.exercises_id", // 关联题目和知识点
            "LEFT JOIN T_knowledge k ON ek.record_id = k.record_id", // 关联知识点表
            "LEFT JOIN T_course c ON k.course_id = c.course_id", // 关联课程表
            "LEFT JOIN T_chapter ch ON k.camera_id = ch.chapter_id", // 关联章节表
            "LEFT JOIN T_question q ON e.exercises_id = q.exercises_id", // 关联题目问题
            "WHERE e.data_type = #{type}", // 根据题类型筛选
            "ORDER BY  ${sort}" // 根据题目 ID 排序
    })

    List<Exercises> getQuestionBanList(@Param("type") String type, @Param("sort") String sort);

    /**
     * 查询具体的题
     * @param exercisesId
     * @return
     */

    @Select({
            "select",
            "       e.exercises_id AS exercisesId,", // 题目 ID
            "       e.title,",
            "       CASE e.difficulty", // 题目难度
            "           WHEN 1 THEN '简单'", // 难度 1：简单
            "           WHEN 2 THEN '中等'", // 难度 2：中等
            "           WHEN 3 THEN '困难'", // 难度 3：困难
            "       END AS difficulty,",
            "       e.question_stem AS questionStem,", // 题目描述
            "       q.question_title AS quesTitle,", // 题目问题
            "       c.course_id AS \"courseInfo.courseId\",", // 课程 ID
            "       c.course_name AS \"courseInfo.courseName\",", // 课程名称
            "       ch.chapter_id AS \"chapterInfo.chapterId\",", // 章节 ID
            "       ch.chapter_name AS \"chapterInfo.chapterName\",", // 章节名称
            "       k.knowledge_content AS knowledgeContent ", // 知识点概述
            "FROM T_exercises e ",
            "LEFT JOIN exec_knowledge ek ON e.exercises_id = ek.exercises_id ", // 关联题目和知识点
            "LEFT JOIN T_knowledge k ON ek.record_id = k.record_id ", // 关联知识点表
            "LEFT JOIN T_course c ON k.course_id = c.course_id ", // 关联课程表
            "LEFT JOIN T_chapter ch ON k.camera_id = ch.chapter_id ", // 关联章节表
            "LEFT JOIN T_question q ON e.exercises_id = q.exercises_id ", // 关联题目问题
            "WHERE e.exercises_id = #{exercisesId}"
    })
    Exercises selectById(@Param("exercisesId") Long exercisesId);

    /**
     * 手动组卷查询
     * 根据title，difficulty，exerciseType查询题信息
     * @param title
     * @param difficulty
     * @param courseId
     * @return
     */
    @Select("<script>" +
            "SELECT exercises_id, title, difficulty, course_id, exercise_type FROM T_exercises " +
            "WHERE 1=1 " +
            "<if test='title != null'> AND title LIKE CONCAT('%', #{title}, '%') </if>" +
            "<if test='difficulty != null'> AND difficulty = #{difficulty} </if>" +
            "<if test='courseId != null'> AND course_id = #{courseId} </if>" +
            "<if test='offset != null and pageSize != null'> LIMIT #{pageSize} OFFSET #{offset} </if> " +
            "</script>")
    List<TExercises> getSearchExercises(
            @Param("title") String title,
            @Param("difficulty") Integer difficulty,
            @Param("courseId") Long courseId,
            @Param("offset") Long offset, // 偏移量
            @Param("pageSize") Long pageSize // 每页数量
    );
    @Select("<script>" +
            "SELECT COUNT(T_exercises.exercises_id) FROM T_exercises " +
            "WHERE 1=1 " +
            "<if test='title != null'> AND title LIKE CONCAT('%', #{title}, '%') </if>" +
            "<if test='difficulty != null'> AND difficulty = #{difficulty} </if>" +
            "<if test='courseId != null'> AND course_id = #{courseId} </if>" +
            "</script>")
    Long getSearchExercisesCount(
                    @Param("title") String title,
                    @Param("difficulty") Integer difficulty,
                    @Param("courseId") Long courseId
            );


    /**
     * 根据题目ID查询题目信息及关联问题
     */
    @Select("SELECT * FROM T_exercises WHERE exercises_id = #{exercisesId}")
    @Results({
            @Result(property = "exercisesId", column = "exercises_id"),
            @Result(property = "chapterId", column = "chapter_id"),
            @Result(property = "title", column = "title"),
            @Result(property = "questionStem", column = "question_stem"),
            @Result(property = "exerciseType", column = "exercise_type"),
            @Result(property = "difficulty", column = "difficulty"),
            @Result(property = "forPractice", column = "for_practice"),
            @Result(property = "forTest", column = "for_test"),
            @Result(property = "createBy", column = "create_by"),
            @Result(property = "createDate", column = "create_date"),
            @Result(property = "isPublic", column = "is_public"),
            @Result(property = "updateBy", column = "update_by"),
            @Result(property = "updateDate", column = "update_date"),
            @Result(property = "eleRemark", column = "ele_remark"),
            @Result(
                    property = "questions",
                    column = "exercises_id",
                    javaType = List.class,
                    many = @Many(select = "findQuestionsByExercisesId")
            )
    })
    Exercises findExercisesWithQuestions(@Param("exercisesId") Long exercisesIds);

    /**
     * 根据题目ID查询关联问题
     */
    @Select("SELECT * FROM T_question WHERE exercises_id = #{exercisesId}")
    List<Question> findQuestionsByExercisesId(@Param("exercisesId") Long exercisesId);

    /**
     * 根据多个题目ID批量查询题目及问题
     */
//    @Select({
//            "<script>",
//            "SELECT ",
//            "  e.exercises_id as exerciseId, e.chapter_id, e.title, e.question_stem, e.exercise_type, ",
//            "  e.difficulty, e.for_practice, e.for_test, e.create_by, e.is_public, ",
//            "  e.update_by, e.update_date, e.ele_remark, ",
//            "       q.question_title AS \"questions.quesTitle\",", // 题目标题
//            "       q.question_type AS \"questions.questionType\",", // 题目类型
//            "       q.answer_options AS \"questions.answerOptions\",", // 题目选项
//            "       q.answer AS \"questions.answer\",", // 题目答案
//            "       q.score AS \"questions.score\",", // 分数
//            "       q.analysis AS \"questions.analysis\",", // 题目解析
//            "       q.display_order AS \"questions.displayOrder\"",
//            "FROM T_exercises e ",
//            "LEFT JOIN T_question q ON e.exercises_id = q.exercises_id ",
//            "WHERE e.exercises_id IN ",
//            "  <foreach item='id' collection='exercisesIds' open='(' separator=',' close=')'>",
//            "    #{id}",
//            "  </foreach> ",
//            "ORDER BY e.exercises_id, q.display_order",
//            "</script>"
//    })
//    List<Map<String, Object>> findBatchExercisesWithQuestions(@Param("exercisesIds") List<Long> exercisesIds);



    /**
     * 根据题目ID数组查询题目及其关联的问题
     * @param exerciseIds 题目ID数组
     * @return 题目列表(包含关联问题)
     */
    @Select({
            "<script>",
            "SELECT * FROM T_exercises",
            "WHERE exercises_id IN",
            "<foreach item='id' collection='array' open='(' separator=',' close=')'>",
            "#{id}",
            "</foreach>",
            "</script>"
    })
    @Results({
            @Result(property = "questions", column = "exercises_id",
                    javaType = List.class,
                    many = @Many(select = "findQuestionsByExerciseId"))
    })
    @Options(statementType = StatementType.PREPARED)
    List<Exercises> findExercisesByIdsWithQuestions(@Param("array") Long[] exerciseIds);

    /**
     * 查询单个题目关联的所有问题（完整字段映射）
     */
    @Select("SELECT * FROM T_question WHERE exercises_id = #{exercisesId}")
    List<Question> findQuestionsByExerciseId(@Param("exercisesId") Long exercisesId);









}
